package com.atguigu.juc.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author yfstart
 * @create 2022-06-22 17:49
 */
public class CompletableFutureAPIThenApply {
  public static void main(String[] args) {

      ExecutorService threadPool = Executors.newFixedThreadPool(3);

      CompletableFuture.supplyAsync(()->{
        try {
          TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println("111");
        return 1;
    },threadPool).thenApply(f->{
        int i = 10 / 0;
        System.out.println("222");
        return f + 2;
    }).thenApply(f->{
        System.out.println("333");
        return f + 3;
    }).whenComplete((v,e)->{
        if (e == null){
            System.out.println("计算结果："+v);
        }
    }).exceptionally(e->{
        e.printStackTrace();
        System.out.println("e.getMessage() = " + e.getMessage());
        return null;
    });

    threadPool.shutdown();

    System.out.println("-----主线程结束，END");
    // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
    // try {
    //   TimeUnit.MILLISECONDS.sleep(1000);
    // } catch (InterruptedException e) {
    //   e.printStackTrace();
    // }
  }
}
